package cn.fanyamin.jms;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * From O'Reilly JMS Book
 *
 */
public class JmsChat implements MessageListener {
	private TopicSession pubSession;
	private TopicPublisher publisher;
	private TopicConnection connection;
	private String username;
	
	public JmsChat(String topicFactory, String topicName, String userName) throws Exception {
		InitialContext ctx = new InitialContext();
		TopicConnectionFactory connFactory = (TopicConnectionFactory)ctx.lookup(topicFactory);
		TopicConnection conn = connFactory.createTopicConnection();
		
		TopicSession pubSession = conn.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);
		TopicSession subSession = conn.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);
		
		Topic chatTopic  = (Topic)ctx.lookup(topicName);
		
		TopicPublisher publisher = pubSession.createPublisher(chatTopic);
		TopicSubscriber subscriber = subSession.createSubscriber(chatTopic, null, true);
		
		subscriber.setMessageListener(this);
		this.connection = conn;
		this.pubSession = pubSession;
		this.publisher = publisher;
		this.username = userName;
		
		conn.start();
	}
	
	@Override
	public void onMessage(Message arg0) {
		try {
			TextMessage txtMsg = (TextMessage)arg0;
			System.out.println(txtMsg.getText());
		} catch(JMSException jmse) {
			jmse.printStackTrace();
		}
		
	}
	
	protected void writeMessage(String text) throws JMSException {
		TextMessage msg = pubSession.createTextMessage();
		msg.setText(username + ": " + text);
		publisher.publish(msg);
	}
	
	public void close() throws JMSException {
		this.connection.close();
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if(args.length != 3) {
			System.out.println("Usage: java ... factoryName topicName userName");
			return;
		}
		try {
			JmsChat chat = new JmsChat(args[0], args[1], args[2]);
			BufferedReader commandLine = new BufferedReader(new InputStreamReader(System.in));
			
			while(true) {
				String s = commandLine.readLine();
				if("exit".equalsIgnoreCase(s)) {
					chat.close();
					System.exit(0);
				} else {
					chat.writeMessage(s);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
